package cn.ito.zjgsu.service.impl;


import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.ito.zjgsu.domain.Department;
import cn.ito.zjgsu.domain.DepartmentExample;
import cn.ito.zjgsu.domain.DepartmentType;
import cn.ito.zjgsu.domain.wrapper.DepartmentWrapper;
import cn.ito.zjgsu.mapping.DepartmentMapper;
import cn.ito.zjgsu.mapping.DepartmentTypeMapper;
import cn.ito.zjgsu.service.DepartmentService;
import cn.ito.zjgsu.vo.DepartmentSavaVo;


@Service
public class DepartmentServiceImpl implements DepartmentService {
	@Resource
	private DepartmentMapper departmentMapper;
	@Autowired
	DepartmentTypeMapper departMapper;

	@Override
	public List<DepartmentWrapper> initDepartmentTree() {
		DepartmentExample departmentExample = new DepartmentExample();
		departmentExample.or().andDepartmentDeleteTagsEqualTo(Department.DEPARTMENT_EXIST_FLAG);
		List<Department> dws = departmentMapper.selectByExample(departmentExample);
		System.out.println("dws"+dws.toString());
		return  DepartmentWrapper.wrapDepartment(dws);
	}
	
	@Override
	public void addDepart(DepartmentSavaVo depart) {
		DepartmentType departmentType = new DepartmentType();
		BeanUtils.copyProperties(depart, departmentType);
		departmentType.setDepartmentCreateTime(new Timestamp(System.currentTimeMillis()));
		departMapper.insert(departmentType);
	}

	@Override
	public void deleteDepart(int departId) {
		deleteSub(departId);
	}

	@Override
	public void updateDepart(DepartmentSavaVo depart) {
		DepartmentType departmentType = new DepartmentType();
		BeanUtils.copyProperties(depart, departmentType);
		departmentType.setDepartmentCreateTime(new Timestamp(System.currentTimeMillis()));
		departMapper.updateByPrimaryKeySelective(departmentType);
	}

	@Override
	public List<DepartmentType> findAllDepart() {
		List<DepartmentType> departments = departMapper.selectAll();
		return departments;
	}

	@Override
	public DepartmentType findDepartById(int id) {
		DepartmentType departmentType = departMapper.selectByPrimaryKey(id);
		return departmentType;
	}

	/**
	 * 删除一个部门时同时删除子部门
	 * @param id
	 */
	public void deleteSub(int id) {
		List<DepartmentType> subDeparts = departMapper.selectByParentId(id);
		if(subDeparts.isEmpty()) {
			departMapper.deleteByPrimaryKey(id);
		}
		else {
			deleteSub(id);
			departMapper.deleteByPrimaryKey(id);
		}
	}

}
